import React, {  } from 'react'
import { Menu } from 'antd';
import { withRouter,Link } from 'react-router-dom'
import { connect } from 'react-redux';
import './LeftNav.css'

import menuList from '../../config/menuConfig'
import memoryUtils from '../../utils/memoryUtils.js';
import { removeUser } from '../../utils/storageUtils';
import { setHeadTitle } from '../../redux/actions';
import { useEffect } from 'react';

const { SubMenu } = Menu

export default connect(state=>({deadTitle:state.headTitle,user:state.user}),{setHeadTitle})(withRouter( function LeftNav(props) {

  const selectKey=props.location.pathname==='/'?'/home':props.location.pathname
  const openedKey=menuList.find(i=>{
    let res=undefined
    if(i.children){
      res= i.children.find(c=>c.path===selectKey)?i:undefined
    }
    return res
  })?.path||'/goods'
  const {user}=props

  const getMenuNodes=(menuList)=>{
    let menus=user.menus
    if(!menus){
      memoryUtils.user={}
      removeUser()
    }
    return  menuList.map(i=>{
      if(i.children){
        return (
          i.children.some(i=>menus.includes(i.path))?
          <SubMenu key={i.path} icon={i.icon} title={i.title}>
            {
              getMenuNodes(i.children)
            }
          </SubMenu>
          :null
        )
      }else{
        return (
          menus.includes(i.path)||i.path==='/home'?
          <Menu.Item icon={i.icon} key={i.path}>
            <Link to={i.path}>{i.title}</Link>
          </Menu.Item>
          :null
        )
      }
    })
  }

  useEffect(()=>{
    function setHeadTitle(path){
      const title=menuList.reduce((pre,cur)=>{
        if(pre) return pre
        if(cur.children){
          pre=cur.children.find(i=>i.path===path)?.title
        }else{
          pre=pre?pre:(cur.path===path?cur.title:'')
        }
        return pre
      },'')
      props.setHeadTitle(title?title:null)
    }
    setHeadTitle(selectKey)
  },[selectKey,props])

  return (
    <div className="left-nav">
      <Link className="left-nav-header" to="/home">
        <h1>硅谷后台</h1>
      </Link>
      <section className="left-nav-content">
        <Menu
          selectedKeys={[selectKey]}
          defaultOpenKeys={[openedKey]}
          mode="inline"
          theme="dark"
        >
          {
            getMenuNodes(menuList)
          }
        </Menu>
      </section>
    </div>
  )
}))